<template>
  <div class="register-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration"></div>

    <!-- 注册卡片 -->
    <div class="register-card">
      <!-- 标题区域 -->
      <div class="register-header">
        <img src="@/assets/logo.png" alt="农村爱心水果售卖系统logo" class="logo">
        <h1 class="title">用户注册</h1>
        <p class="subtitle">填写以下信息完成注册，成为爱心水果购买者</p>
      </div>

      <!-- 注册表单 -->
      <el-form
          :model="registerForm"
          ref="registerFormRef"
          :rules="registerRules"
          class="register-form"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名（3-20个字符）"
              prefix-icon="User"
              autocomplete="off"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（6-20个字符）"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号码" />
        </el-form-item>

        <!-- 验证码 + 发送按钮 -->
        <el-form-item label="验证码" prop="verifyCode">
          <div style="display:flex; gap:8px; width:100%;">
            <el-input v-model="registerForm.verifyCode" placeholder="请输入验证码" />
            <el-button
                type="primary"
                :disabled="sending || countdown > 0"
                @click="onSendCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : (sending ? '发送中...' : '发送验证码') }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="registerForm.agreement" class="agreement-checkbox">
            我已阅读并同意
            <el-link type="primary">《用户服务协议》</el-link>
            和
            <el-link type="primary">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-button
            type="primary"
            class="register-btn"
            @click="handleRegister"
            :loading="loading"
        >
          注册
        </el-button>

        <div class="login-link">
          已有账号?
          <el-link type="primary" @click="goToLogin">
            立即登录
          </el-link>
        </div>
      </el-form>
    </div>

    <!-- 页脚 -->
    <footer class="register-footer">
      © 2025 农村爱心水果售卖系统 版权所有
    </footer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import registerApi from '@/api/register_api.js'; // 注册接口

// 路由实例
const router = useRouter();

// 加载状态
const loading = ref(false);

// 表单引用
const registerFormRef = ref(null);

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  verifyCode: '',
  agreement: false
});

// 发送状态和倒计时
const sending = ref(false);
const countdown = ref(0);  // 初始化倒计时

// 启动倒计时
let timer = null;
const startCountdown = (sec = 60) => {
  countdown.value = sec;
  timer && clearInterval(timer);
  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 发送验证码：把 phone 发给后端，后端会把验证码邮件到你在后端配置的邮箱
const onSendCode = async () => {
  if (countdown.value > 0 || sending.value) return;  // 如果倒计时还没结束或正在发送中，返回

  if (!/^1[3-9]\d{9}$/.test(registerForm.phone)) {  // 校验手机号格式
    return ElMessage.error('请先输入正确的手机号');
  }

  try {
    sending.value = true;
    await registerApi.sendCode(registerForm.phone);  // 发送验证码请求
    ElMessage.success('验证码已发送，请查收邮箱');
    startCountdown(60);  // 启动倒计时
  } catch (e) {
    ElMessage.error('验证码发送失败，请稍后重试');
  } finally {
    sending.value = false;
  }
};

// 处理注册
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate();  // 验证表单
  } catch (error) {
    return ElMessage.error('请完善注册信息');
  }

  loading.value = true;
  try {
    const response = await registerApi.register({
      username: registerForm.username,
      password: registerForm.password,
      phone: registerForm.phone,
      verifyCode: registerForm.verifyCode
    });

    ElMessage.success('注册成功，请登录');
    router.push({ path: '/login', query: { username: registerForm.username } });
  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error(error.response?.data?.message || '注册失败，请检查信息');
  } finally {
    loading.value = false;
  }
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f0f9f0;
  position: relative;
  overflow: hidden;
  padding: 20px 0;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image:
      radial-gradient(circle at 20% 30%, rgba(46, 125, 50, 0.05) 0%, transparent 40%),
      radial-gradient(circle at 80% 70%, rgba(46, 125, 50, 0.05) 0%, transparent 40%);
  z-index: 0;
}

/* 注册卡片 */
.register-card {
  width: 100%;
  max-width: 500px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 30px;
  z-index: 1;
}

/* 标题区域 */
.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  height: 60px;
  margin-bottom: 15px;
  object-fit: contain;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #2e7d32;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
}

/* 注册表单 */
.register-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.verify-code-container {
  display: flex;
  gap: 10px;
}

.verify-code-input {
  flex: 1;
}

.send-code-btn {
  width: 130px;
}

.agreement-checkbox {
  color: #666;
  font-size: 14px;
}

.register-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  background-color: #2e7d32;
  border-color: #2e7d32;
}

.register-btn:hover {
  background-color: #1b5e20;
  border-color: #1b5e20;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

/* 页脚 */
.register-footer {
  margin-top: 30px;
  color: #999;
  font-size: 12px;
  text-align: center;
  z-index: 1;
}

/* 响应式调整 */
@media (max-width: 576px) {
  .register-card {
    margin: 0 20px;
    padding: 25px 20px;
  }

  .title {
    font-size: 22px;
  }

  .verify-code-container {
    flex-direction: column;
  }

  .send-code-btn {
    width: 100%;
  }
}
</style>
